package com.wmlive.hhvideo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.wmlive.hhvideo.heihei.beans.main.UserBehavior;
import com.wmlive.hhvideo.service.presenter.UserBehaviorPresenter;
import com.wmlive.hhvideo.service.view.UserBehaviorView;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.networklib.util.RxBus;

import io.reactivex.Flowable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

/**
 * 后台上传用户行为
 * Created by vhawk on 2017/6/20.
 */

public class DCService extends Service implements UserBehaviorView {

    private static final String TAG = "DCService";
    CompositeDisposable compositeDisposable;
    private UserBehaviorPresenter userBehaviorPresenter;

    @Override
    public void onCreate() {
        super.onCreate();
        KLog.v(TAG, "onCreate");
        userBehaviorPresenter = new UserBehaviorPresenter(this);
        onRxBusEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        KLog.v(TAG, "onDestroy");
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
        }
        userBehaviorPresenter.destroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * RxBus注册事件
     */
    private void onRxBusEvent() {
        getCompositeDisposable().add(toFlowable(UserBehavior.class).subscribe(new Consumer<UserBehavior>() {
            @Override
            public void accept(UserBehavior userBehavior) throws Exception {
                KLog.v(TAG, userBehavior.toString());
                userBehaviorPresenter.sendUserBehavior(userBehavior);
            }
        }));
    }

    protected CompositeDisposable getCompositeDisposable() {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        return compositeDisposable;
    }

    protected <T> Flowable<T> toFlowable(Class<T> type) {
        return RxBus.getInstance().toFlowable(type);
    }

    @Override
    public void onRequestDataError(int requestCode, String message) {

    }

    @Override
    public void handleNetError() {

    }

    @Override
    public void handleUserBehaviorSucceed() {

    }

    @Override
    public void handleUserBehaviorFailure(String message) {
        KLog.v(TAG, message);
    }

}
